Popular Searches
Popular Course Categories
Popular Courses

CSV Data

Data-Driven Testing

CSV Data in Selenium Automation

CSV Data refers to test data stored in a Comma-Separated Values (CSV) file. CSV files are simple, lightweight, and widely used for storing structured test data such as usernames, passwords, search keywords, product information, registration details, expected results, and other input combinations.

In Selenium automation, CSV data is commonly used with Java and TestNG to implement data-driven testing. Instead of hard-coding many test-data values directly inside test methods, the data can be maintained in a CSV file and loaded dynamically during test execution.

Using CSV data makes automation frameworks easier to maintain because test logic and test data can be separated. When test data changes, testers can often update the CSV file without modifying the main Selenium test logic.

Course Resource: Selenium Training | Register for Course Demo


1. What is CSV?

CSV stands for Comma-Separated Values. It is a text-based file format used to store tabular data.

Each line generally represents one record, while commas separate the individual values within that record.

Username,Password,Role

admin,admin123,Admin

manager,manager123,Manager

employee,employee123,Employee

In this example, the first row represents the column headers and the remaining rows contain test data.


2. Why is CSV Data Important in Selenium?

CSV files are useful when Selenium tests need to execute the same workflow using many different sets of data.

  • Separates test data from automation logic.
  • Reduces hard-coded test data.
  • Supports data-driven testing.
  • Makes test data easier to update.
  • Allows testers to maintain large collections of test data.
  • Can be reused by multiple test cases.
  • Works well with Selenium WebDriver and TestNG.
  • Can be integrated with CI/CD automation.
  • Is easy to create and inspect.
  • Can be generated or modified programmatically.


3. CSV Data Flow

The basic CSV-driven Selenium execution flow is:

CSV File

    |

    v

CSV Reader

    |

    v

Test Data Objects

    |

    v

@DataProvider

    |

    v

TestNG Test Method

    |

    v

Selenium WebDriver

    |

    v

Web Application

    |

    v

Assertions

    |

    v

Test Report


4. Example CSV File

Consider a file named loginData.csv:

username,password,expectedResult

admin,admin123,success

manager,manager123,success

employee,employee123,success

invalid,wrong123,failure

Each row represents one login scenario.

UsernamePasswordExpected Result
adminadmin123success
managermanager123success
employeeemployee123success
invalidwrong123failure


5. CSV Headers

A CSV file can contain a header row that identifies the meaning of each column.

username,password,expectedResult

Headers make test data easier to understand and allow CSV-reading utilities to map values to meaningful field names.


6. Reading CSV Data in Java

Java provides several approaches for reading CSV files. A simple approach is to use BufferedReader and process each line.

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

public class CSVReaderExample {

 

    public static void main(String[] args) throws IOException {

 

        BufferedReader reader =

                new BufferedReader(new FileReader("loginData.csv"));

 

        String line;

 

        while ((line = reader.readLine()) != null) {

            System.out.println(line);

        }

 

        reader.close();

    }

}

This approach is suitable for simple CSV structures where commas are not used inside individual field values.


7. Reading CSV Using try-with-resources

The try-with-resources statement is preferable because it automatically closes the file resource.

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOException;

 

public class CSVReader {

 

    public static void readFile(String filePath) throws IOException {

 

        try (BufferedReader reader =

                     new BufferedReader(new FileReader(filePath))) {

 

            String line;

 

            while ((line = reader.readLine()) != null) {

                System.out.println(line);

            }

        }

    }

}


8. Splitting CSV Rows

A simple CSV row can be split using the Java split() method.

String line = "admin,admin123,success";

 

String[] values = line.split(",");

 

System.out.println(values[0]);

System.out.println(values[1]);

System.out.println(values[2]);

The output is:

admin

admin123

success


9. Basic CSV Reader Utility

A reusable utility class can be created to read CSV records.

import java.io.BufferedReader;

import java.io.FileReader;

import java.util.ArrayList;

import java.util.List;

 

public class CSVReader {

 

    public static List<String[]> readCSV(String filePath) {

 

        List<String[]> data = new ArrayList<>();

 

        try (BufferedReader reader =

                     new BufferedReader(new FileReader(filePath))) {

 

            String line;

 

            while ((line = reader.readLine()) != null) {

                data.add(line.split(","));

            }

 

        } catch (Exception e) {

            e.printStackTrace();

        }

 

        return data;

    }

}


10. Skipping the Header Row

When a CSV file contains column headers, the header should normally not be passed to the test method as test data.

try (BufferedReader reader =

             new BufferedReader(new FileReader("loginData.csv"))) {

 

    String line;

    boolean header = true;

 

    while ((line = reader.readLine()) != null) {

 

        if (header) {

            header = false;

            continue;

        }

 

        System.out.println(line);

    }

}


11. Converting CSV Data into Object[][]

TestNG Data Providers commonly use Object[][]. Therefore, CSV rows can be converted into an Object[][] structure.

@DataProvider(name = "csvData")

public Object[][] csvData() {

 

    return new Object[][] {

        {"admin", "admin123"},

        {"manager", "manager123"},

        {"employee", "employee123"}

    };

}

In a real framework, these values can be loaded dynamically from the CSV file rather than being hard-coded.


12. CSV Data with TestNG DataProvider

One of the most common approaches is to read CSV data inside a TestNG Data Provider.

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class LoginTest {

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() {

 

        return new Object[][] {

            {"admin", "admin123"},

            {"manager", "manager123"},

            {"employee", "employee123"}

        };

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(String username, String password) {

 

        System.out.println(username);

        System.out.println(password);

    }

}

In a production framework, the Data Provider can obtain these rows from the CSV reader.


13. CSV Reader with DataProvider

The following example demonstrates the basic structure for loading CSV data into a Data Provider.

import java.io.BufferedReader;

import java.io.FileReader;

import java.util.ArrayList;

import java.util.List;

 

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class CSVDataTest {

 

    @DataProvider(name = "csvData")

    public Object[][] csvData() {

 

        List<Object[]> data = new ArrayList<>();

 

        try (BufferedReader reader =

                     new BufferedReader(new FileReader("loginData.csv"))) {

 

            String line;

            boolean header = true;

 

            while ((line = reader.readLine()) != null) {

 

                if (header) {

                    header = false;

                    continue;

                }

 

                String[] values = line.split(",");

 

                data.add(new Object[] {

                    values[0],

                    values[1],

                    values[2]

                });

            }

 

        } catch (Exception e) {

            throw new RuntimeException("Unable to read CSV file", e);

        }

 

        return data.toArray(new Object[0][]);

    }

 

    @Test(dataProvider = "csvData")

    public void loginTest(

            String username,

            String password,

            String expectedResult) {

 

        System.out.println(username);

        System.out.println(password);

        System.out.println(expectedResult);

    }

}


14. CSV Data with Selenium WebDriver

CSV data can be used to supply login credentials to a Selenium test.

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class LoginCSVTest {

 

    WebDriver driver;

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() {

 

        return new Object[][] {

            {"admin", "admin123"},

            {"manager", "manager123"},

            {"employee", "employee123"}

        };

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(String username, String password) {

 

        driver = new ChromeDriver();

 

        driver.get("https://example.com/login");

 

        driver.findElement(By.id("username"))

                .sendKeys(username);

 

        driver.findElement(By.id("password"))

                .sendKeys(password);

 

        driver.findElement(By.id("loginButton"))

                .click();

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


15. CSV Login Testing

Login testing is one of the most common applications of CSV-driven automation.

Example CSV:

username,password,expected

admin,admin123,success

manager,manager123,success

invalid,wrong123,failure

The same Selenium login workflow can execute against every row.


16. CSV Search Testing

CSV files can store multiple search keywords.

searchText,expectedResult

Laptop,Laptop

Mobile,Mobile

Headphones,Headphones

Keyboard,Keyboard

These values can be supplied to a Selenium search test.

@DataProvider(name = "searchData")

public Object[][] searchData() {

 

    return new Object[][] {

        {"Laptop", "Laptop"},

        {"Mobile", "Mobile"},

        {"Headphones", "Headphones"},

        {"Keyboard", "Keyboard"}

    };

}

 

@Test(dataProvider = "searchData")

public void searchTest(

        String searchText,

        String expectedResult) {

 

    System.out.println(searchText);

    System.out.println(expectedResult);

}


17. CSV Registration Data

Registration forms can contain multiple fields such as name, email, mobile number, city, and password.

name,email,mobile,city

John,[email protected],9876543210,Mumbai

David,[email protected],9876543211,Delhi

Robert,[email protected],9876543212,Pune

A Data Provider can supply these values to a Selenium registration test.


18. CSV Product Data

E-commerce automation can use CSV files to store product-related test data.

product,quantity,category

Laptop,1,Electronics

Mobile,2,Electronics

Shoes,1,Fashion

Book,3,Books

The test can use these values to search for products, add them to a cart, and validate quantities or categories.


19. CSV with Expected Results

Expected results can be included as columns in the CSV file.

username,password,expectedMessage

admin,admin123,Login Successful

invalid,wrong123,Invalid Credentials

,admin123,Username Required

This allows the same test to perform both positive and negative validation.


20. Positive and Negative Testing with CSV

CSV files are particularly useful for maintaining multiple positive and negative test scenarios.

UsernamePasswordScenario
adminadmin123Valid Login
invalidadmin123Invalid Username
adminwrong123Invalid Password
admin123Missing Username


21. CSV Data and Assertions

Expected values from CSV can be used directly in assertions.

@Test(dataProvider = "loginData")

public void loginTest(

        String username,

        String password,

        String expectedMessage) {

 

    String actualMessage = "Login Successful";

 

    Assert.assertEquals(actualMessage, expectedMessage);

}

This approach makes the expected result part of the test data rather than hard-coding it inside the test method.


22. CSV Data with Multiple Data Types

CSV files store values as text, so values may need to be converted into the required Java data type.

product,quantity,price,available

Laptop,2,75000,true

Mobile,3,25000,true

Tablet,1,35000,false

The values can be converted as follows:

int quantity = Integer.parseInt(values[1]);

double price = Double.parseDouble(values[2]);

boolean available = Boolean.parseBoolean(values[3]);


23. CSV Data and Page Object Model

CSV data works well with the Page Object Model (POM). The CSV file provides test data while Page Classes contain Selenium interaction logic.

CSV File

   |

   v

Data Provider

   |

   v

Test Class

   |

   v

LoginPage

   |

   v

Selenium WebDriver

   |

   v

Application

This separation keeps the automation framework organized and maintainable.


24. CSV Data with POM Example

public class LoginPage {

 

    WebDriver driver;

 

    By username = By.id("username");

    By password = By.id("password");

    By loginButton = By.id("loginButton");

 

    public LoginPage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void login(String user, String pass) {

 

        driver.findElement(username).sendKeys(user);

        driver.findElement(password).sendKeys(pass);

        driver.findElement(loginButton).click();

    }

}

The test class can receive CSV values and pass them to the Page Object.


25. CSV File Location

In a Maven-based Selenium project, test-data files can be stored under the test resources directory.

project

|

|-- pom.xml

|

|-- src

|   |-- test

|       |-- java

|       |   |-- tests

|       |   |-- pages

|       |   |-- utilities

|       |

|       |-- resources

|           |-- testdata

|               |-- loginData.csv

|               |-- searchData.csv

|               |-- productData.csv


26. Reading CSV from src/test/resources

Using the classpath for test data is preferable to relying on an absolute file path.

InputStream input =

        getClass()

        .getClassLoader()

        .getResourceAsStream("testdata/loginData.csv");

This approach makes the project more portable across different machines and CI environments.


27. Absolute Path vs Relative Path

Absolute PathRelative/Classpath Path
Depends on a specific machineMore portable
May fail on another computerWorks well across environments
Harder for CI/CDBetter suited for CI/CD
Example: C:\data\login.csvExample: testdata/loginData.csv


28. CSV Quoting Problem

A simple split(",") approach is not a complete CSV parser. CSV values can contain commas, quotation marks, and line breaks.

For example:

name,address

John,"Mumbai, Maharashtra"

Splitting this row directly using split(",") can produce incorrect columns because the address itself contains a comma.

For complex CSV files, a dedicated CSV library should be used.


29. Using OpenCSV

OpenCSV is a Java library designed for reading and writing CSV files and handling CSV-specific syntax more reliably than a simple string split.

A Maven dependency can be added according to the version approved for the project:

<dependency>

    <groupId>com.opencsv</groupId>

    <artifactId>opencsv</artifactId>

    <version>5.12.0</version>

    <scope>test</scope>

</dependency>

The exact library version should be managed centrally in the project dependency configuration.


30. Reading CSV with OpenCSV

import com.opencsv.CSVReader;

import java.io.FileReader;

 

public class OpenCSVExample {

 

    public static void main(String[] args) throws Exception {

 

        try (CSVReader reader =

                     new CSVReader(new FileReader("loginData.csv"))) {

 

            String[] row;

 

            while ((row = reader.readNext()) != null) {

                System.out.println(row[0]);

                System.out.println(row[1]);

            }

        }

    }

}


31. OpenCSV with TestNG DataProvider

OpenCSV can be combined with TestNG to create a reusable CSV-driven Data Provider.

@DataProvider(name = "csvData")

public Object[][] csvData() throws Exception {

 

    List<Object[]> data = new ArrayList<>();

 

    try (CSVReader reader =

                 new CSVReader(new FileReader("loginData.csv"))) {

 

        String[] row;

        boolean header = true;

 

        while ((row = reader.readNext()) != null) {

 

            if (header) {

                header = false;

                continue;

            }

 

            data.add(new Object[] {

                row[0],

                row[1],

                row[2]

            });

        }

    }

 

    return data.toArray(new Object[0][]);

}


32. CSV Data with Apache Commons CSV

Another option is Apache Commons CSV, which provides CSV parsing functionality and supports common CSV formats.

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-csv</artifactId>

    <version>1.14.1</version>

    <scope>test</scope>

</dependency>

The library version should be checked against the project's Java version and dependency-management standards.


33. Header-Based CSV Reading

When CSV headers are available, using column names can make test-data handling easier to understand.

username,password,role

admin,admin123,Admin

Conceptually, the application can access:

username

password

role

instead of relying only on numeric column indexes.


34. CSV Data and TestNG Reports

When each CSV row becomes a separate TestNG invocation, a failed invocation can be associated with the corresponding test-data combination.

LoginTest

   |

   |-- admin / admin123       PASS

   |-- manager / manager123   PASS

   |-- invalid / wrong123     FAIL

For better reporting, frameworks can include non-sensitive test-data identifiers in test names or logs.


35. CSV Data and Parallel Execution

CSV-driven tests can be executed in parallel when the test framework is designed for thread safety.

@DataProvider(

    name = "csvData",

    parallel = true

)

public Object[][] csvData() {

    return new Object[][] {

        {"user1", "pass1"},

        {"user2", "pass2"},

        {"user3", "pass3"}

    };

}

When Selenium tests run concurrently, each test invocation should generally use an isolated WebDriver session.


36. CSV Data and Thread Safety

CSV data itself is usually read-only during test execution, but the surrounding automation framework must still be thread-safe.

A safe architecture is:

CSV Data

    |

    v

Data Provider

    |

    +------ Thread 1 ------ WebDriver 1

    |

    +------ Thread 2 ------ WebDriver 2

    |

    +------ Thread 3 ------ WebDriver 3

Sharing one mutable WebDriver instance across concurrent tests can cause test interference.


37. CSV Data for Environment Testing

CSV files can store environment-specific test information.

environment,url

QA,https://qa.example.com

Stage,https://stage.example.com

Production,https://www.example.com

A Data Provider can supply the environment and URL to the test.


38. CSV Data for Browser Testing

Browser information can also be maintained in CSV data.

browser

chrome

firefox

edge

The test framework can pass the browser value to a WebDriver factory.


39. CSV Data for User Roles

username,role

admin,Admin

manager,Manager

employee,Employee

customer,Customer

This type of data can be used for role-based access testing.


40. CSV Data for Search Filters

keyword,category,minPrice,maxPrice

Laptop,Electronics,30000,100000

Shoes,Fashion,1000,10000

Book,Books,200,3000

The Selenium test can use these values to validate search and filtering functionality.


41. CSV Data for E-Commerce Testing

An e-commerce test suite can use CSV files for product and checkout scenarios.

product,quantity,paymentMethod,expectedStatus

Laptop,1,Card,Success

Mobile,2,UPI,Success

Shoes,1,COD,Success

One reusable test method can process each row.


42. CSV Data for API and UI Testing

CSV data is not limited to Selenium UI testing. The same test-data source can be used for API testing, database validation, and UI automation.

Test Data

    |

    +---- Selenium UI Test

    |

    +---- API Test

    |

    +---- Database Validation

    |

    +---- Integration Test

This can help maintain consistency when several testing layers use the same business scenarios.


43. CSV Data with Reusable Utility Class

A reusable CSV utility reduces duplicate file-reading code across test classes.

public class CSVUtils {

 

    public static List<String[]> readCSV(String path) {

 

        List<String[]> rows = new ArrayList<>();

 

        try (BufferedReader reader =

                     new BufferedReader(new FileReader(path))) {

 

            String line;

 

            while ((line = reader.readLine()) != null) {

                rows.add(line.split(","));

            }

 

        } catch (Exception e) {

            throw new RuntimeException(

                    "Unable to read CSV: " + path, e);

        }

 

        return rows;

    }

}


44. CSV Data Utility Responsibilities

A good CSV utility can handle responsibilities such as:

  • Locating the CSV file.
  • Opening the file.
  • Reading records.
  • Handling headers.
  • Handling empty rows.
  • Parsing CSV values.
  • Converting values into required types.
  • Handling file-related exceptions.
  • Returning data in a reusable structure.


45. Handling Empty CSV Values

CSV data may contain empty fields.

username,password,email

admin,admin123,[email protected]

manager,,[email protected]

,employee123,[email protected]

The test should explicitly define how empty values are handled.

if (password == null || password.isBlank()) {

    System.out.println("Password is empty");

}


46. Handling Missing CSV Files

A missing CSV file should produce a clear error message rather than silently returning incorrect test data.

File file = new File("loginData.csv");

 

if (!file.exists()) {

    throw new RuntimeException(

        "CSV file not found: " + file.getAbsolutePath()

    );

}


47. Handling Invalid CSV Data

Test data should be validated before it is passed to Selenium.

if (values.length < 3) {

    throw new RuntimeException(

        "Invalid CSV row: insufficient columns"

    );

}

Validation helps identify data-quality problems early.


48. CSV Data Validation

Before executing a test, values can be checked for expected formats.

String email = values[1];

 

if (!email.contains("@")) {

    throw new IllegalArgumentException(

        "Invalid email: " + email

    );

}

More robust applications should use appropriate validation rules rather than relying only on simple string checks.


49. CSV Data vs Excel Data

FeatureCSVExcel
FormatPlain textSpreadsheet workbook
ComplexitySimpleMore features
Multiple SheetsNoYes
File Size/ProcessingGenerally lightweightCan be heavier
Easy to EditYesYes
Best UseSimple tabular test dataRich structured test data


50. CSV Data vs Hard-Coded Data

Hard-Coded DataCSV Data
Stored inside source codeStored in external file
More difficult to updateEasier to update
Mixes data and test logicSeparates data and test logic
Less reusableMore reusable
Can increase code duplicationSupports data-driven execution


51. CSV Data vs DataProvider

CSV and DataProvider are not competing concepts. They are commonly used together.

CSVDataProvider
Stores test dataSupplies data to test methods
External data sourceTestNG execution mechanism
Contains rows and columnsConverts data into test invocations
Can be reused by multiple testsCan be reused by multiple test methods


52. CSV Data vs Properties File

CSVProperties
Best for multiple recordsBest for key-value configuration
Multiple rows and columnsKey-value pairs
Useful for test datasetsUseful for URLs and configuration
Example: login recordsExample: base URL


53. CSV Data vs JSON

CSVJSON
Tabular structureHierarchical structure
Simple data relationshipsSupports nested structures
Easy for spreadsheet-style dataUseful for complex structured data
LightweightFlexible


54. Common Mistakes with CSV Data

  • Using an incorrect file path.
  • Forgetting to skip the header row.
  • Using split(",") for complex CSV files containing quoted commas.
  • Not validating the number of columns.
  • Ignoring empty values.
  • Using incorrect data types.
  • Hard-coding absolute paths.
  • Storing sensitive credentials in plain text.
  • Not handling file-reading exceptions.
  • Creating very large in-memory Object[][] structures unnecessarily.
  • Not identifying which CSV row caused a failure.
  • Sharing unsafe WebDriver instances during parallel execution.


55. Best Practices for CSV Data

  • Keep CSV files in a dedicated test-data or resources directory.
  • Use meaningful column headers.
  • Keep one logical dataset per CSV file where practical.
  • Use a reusable CSV reader utility.
  • Use a dedicated CSV parsing library for complex CSV syntax.
  • Validate the CSV structure before test execution.
  • Avoid absolute file paths.
  • Keep sensitive credentials out of source-controlled CSV files.
  • Use expected-result columns for data-driven assertions.
  • Log enough information to identify failed records without exposing secrets.
  • Use DataProviders to connect CSV data with TestNG tests.
  • Use POM to separate Selenium interaction logic from test data.
  • Use parallel execution only when the framework is thread-safe.


56. Security Considerations

CSV files are plain-text files, so sensitive information stored inside them can be easily exposed.

Avoid storing real production passwords, API keys, access tokens, or other secrets in source-controlled CSV files.

For sensitive test credentials, use appropriate environment variables, secret-management systems, or CI/CD secret stores.


57. CSV Data and Maven

CSV-driven Selenium projects can be executed through Maven.

mvn test

Maven can manage Selenium, TestNG, CSV parsing libraries, and other project dependencies.


58. CSV Data and CI/CD

CSV-based tests can run in CI/CD pipelines as long as the CSV files are available to the test environment.

Developer Commit

      |

      v

CI/CD Pipeline

      |

      v

Maven Build

      |

      v

TestNG

      |

      v

CSV Data

      |

      v

Selenium Tests

      |

      v

Assertions

      |

      v

Test Report


59. CSV Data and Regression Testing

Regression suites often execute the same test flow against many combinations of input data. CSV files provide a convenient way to maintain these combinations.

For example, a regression test may validate:

  • Multiple usernames.
  • Multiple search keywords.
  • Multiple products.
  • Multiple user roles.
  • Multiple payment methods.
  • Multiple expected outcomes.


60. Practical Selenium CSV Project Structure

selenium-project

|

|-- pom.xml

|

|-- src

|   |-- test

|       |-- java

|       |   |-- tests

|       |   |   |-- LoginTest.java

|       |   |   |-- SearchTest.java

|       |   |   |-- ProductTest.java

|       |   |

|       |   |-- pages

|       |   |   |-- LoginPage.java

|       |   |   |-- SearchPage.java

|       |   |

|       |   |-- utilities

|       |       |-- CSVReader.java

|       |       |-- DriverFactory.java

|       |

|       |-- resources

|           |-- testdata

|               |-- loginData.csv

|               |-- searchData.csv

|               |-- productData.csv


61. Complete Practical CSV Login Example

The following example demonstrates the overall structure of a Selenium TestNG login test using CSV-style data.

import java.util.ArrayList;

import java.util.List;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.DataProvider;

import org.testng.annotations.Test;

 

public class LoginCSVTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

        driver.manage().window().maximize();

        driver.get("https://example.com/login");

    }

 

    @DataProvider(name = "loginData")

    public Object[][] loginData() {

 

        List<Object[]> data = new ArrayList<>();

 

        data.add(new Object[] {

            "admin",

            "admin123",

            "success"

        });

 

        data.add(new Object[] {

            "manager",

            "manager123",

            "success"

        });

 

        data.add(new Object[] {

            "invalid",

            "wrong123",

            "failure"

        });

 

        return data.toArray(new Object[0][]);

    }

 

    @Test(dataProvider = "loginData")

    public void loginTest(

            String username,

            String password,

            String expectedResult) {

 

        driver.findElement(By.id("username"))

                .sendKeys(username);

 

        driver.findElement(By.id("password"))

                .sendKeys(password);

 

        driver.findElement(By.id("loginButton"))

                .click();

 

        String actualResult = "success";

 

        Assert.assertEquals(actualResult, expectedResult);

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}

In a production implementation, the values inside the DataProvider would be loaded from the CSV file instead of being directly added in Java code.


62. Real-World CSV Automation Architecture

                  CSV Files

                      |

          +-----------+-----------+

          |           |           |

       Login       Search      Products

          |           |           |

          +-----------+-----------+

                      |

                      v

                CSV Reader

                      |

                      v

                 DataProvider

                      |

                      v

                 Test Classes

                      |

                      v

                Page Objects

                      |

                      v

              Selenium WebDriver

                      |

                      v

                 Application

                      |

                      v

                  Assertions

                      |

                      v

                   Reports


63. Advantages of CSV Data

  • Simple: CSV is easy to create and understand.
  • Portable: CSV files can be used across operating systems and tools.
  • Lightweight: CSV has a simple text-based structure.
  • Reusable: The same dataset can support multiple tests.
  • Maintainable: Test data can be updated separately from test code.
  • Data-Driven: Multiple test scenarios can be executed using one test method.
  • CI/CD Friendly: CSV files can be included with automation projects.
  • Easy Integration: CSV can be connected with TestNG DataProviders and Selenium.


64. Limitations of CSV Data

  • CSV does not naturally support multiple worksheets.
  • It has limited support for complex hierarchical data.
  • Complex quoting and embedded commas require proper CSV parsing.
  • All values are initially represented as text.
  • Large files can require significant memory when converted into Object[][].
  • CSV files are not suitable for storing secrets securely.
  • Relationships between complex datasets are difficult to represent.


65. When Should You Use CSV Data?

CSV is a good choice when the test data is primarily tabular and does not require complex nested structures.

  • Login test data.
  • Registration data.
  • Search keywords.
  • Product information.
  • User roles.
  • Expected results.
  • Simple environment combinations.
  • Simple browser combinations.
  • Regression test datasets.


66. When Should You Consider Another Data Source?

Another data source may be more suitable when the test data has complex relationships, nested structures, large volumes, or strong security requirements.

  • Use JSON for hierarchical or nested data.
  • Use Excel when spreadsheet features or multiple sheets are required.
  • Use databases when test data is large or dynamically generated.
  • Use properties files for simple key-value configuration.
  • Use secure secret-management systems for sensitive credentials.


67. Interview Questions on CSV Data

1. What is CSV?

CSV stands for Comma-Separated Values and is a text-based format for storing tabular data.

2. Why is CSV useful in Selenium?

CSV allows Selenium tests to obtain multiple test-data combinations without hard-coding every value inside the test method.

3. Can CSV be used with TestNG?

Yes. CSV data can be read by Java code and supplied to TestNG through a DataProvider.

4. What is a DataProvider?

A DataProvider is a TestNG mechanism that supplies data to test method invocations.

5. Can CSV data be used with POM?

Yes. CSV provides test data while Page Objects contain Selenium interaction logic.

6. Can CSV data be used for login testing?

Yes. Login usernames, passwords, and expected results can be stored in CSV.

7. Can CSV store expected results?

Yes. Expected results can be stored as separate columns.

8. What Java class can read a simple CSV file?

BufferedReader can be used for simple CSV files.

9. Why might split(",") be insufficient?

Because valid CSV data can contain quoted values, commas inside fields, quotation marks, or line breaks.

10. Which libraries can parse CSV files?

Libraries such as OpenCSV and Apache Commons CSV can be used for more robust CSV parsing.

11. Should CSV passwords be stored in source control?

Real or sensitive credentials should generally not be stored as plain text in source-controlled files.

12. Can CSV tests run in parallel?

Yes, when the TestNG DataProvider and surrounding Selenium framework are designed for thread-safe execution.

13. What is the benefit of CSV over hard-coded data?

CSV separates test data from test logic and makes datasets easier to maintain and expand.

14. Can CSV data be used in CI/CD?

Yes. CSV files can be packaged with the test project or supplied through the CI/CD environment.

15. How should CSV files be stored in Maven projects?

They can commonly be placed under src/test/resources in a dedicated testdata directory.

16. What happens if the CSV file is missing?

The test framework should report a clear file-not-found or data-loading error.

17. Why should headers be skipped?

Headers describe the columns and generally should not be treated as actual test data.

18. Can CSV contain different data types?

CSV stores values as text, but Java code can convert those values into integers, booleans, doubles, and other required types.

19. Can the same CSV be used by multiple tests?

Yes. A reusable CSV utility or DataProvider can expose the same dataset to multiple test methods.

20. What is the main purpose of CSV-driven testing?

The main purpose is to execute reusable test logic against multiple externally maintained data combinations.


68. Quick Reference Table

ConceptDescription
CSVComma-Separated Values file format
CSV ReaderUtility used to read CSV records
DataProviderTestNG mechanism for supplying test data
Object[][]Common structure used for multiple test-data rows
OpenCSVJava library for CSV parsing
Apache Commons CSVJava library for parsing CSV formats
POMSeparates page interaction logic from test logic
Test DataInput values used during test execution
Expected ResultExpected application behavior stored with test data
src/test/resourcesCommon location for test-data files in Maven projects


69. Learning Roadmap for CSV Data

  1. Understand CSV file structure.
  2. Create CSV files with headers.
  3. Learn Java file handling.
  4. Read CSV using BufferedReader.
  5. Understand CSV rows and columns.
  6. Learn how to skip CSV headers.
  7. Convert CSV rows into Java objects.
  8. Connect CSV data with TestNG DataProvider.
  9. Use CSV data with Selenium WebDriver.
  10. Use CSV data with assertions.
  11. Combine CSV data with Page Object Model.
  12. Build reusable CSV reader utilities.
  13. Learn OpenCSV or Apache Commons CSV.
  14. Handle invalid and missing CSV data.
  15. Integrate CSV testing with Maven.
  16. Execute CSV-driven tests in CI/CD.
  17. Implement parallel CSV-driven testing safely.


70. Practical Exercises

  1. Create a CSV file containing five usernames and passwords.
  2. Read the CSV file using BufferedReader.
  3. Skip the CSV header row.
  4. Convert CSV rows into Object[][].
  5. Create a TestNG DataProvider using CSV data.
  6. Build a Selenium login test using CSV credentials.
  7. Add expected login results to the CSV file.
  8. Create a CSV-driven search test.
  9. Create a registration test using CSV data.
  10. Create an e-commerce product test using CSV data.
  11. Create a reusable CSVReader utility.
  12. Use OpenCSV to handle quoted CSV values.
  13. Combine CSV data with Page Object Model.
  14. Run CSV-driven tests through Maven.
  15. Execute independent CSV test cases in parallel.


71. Final Practical Example

Suppose an e-commerce application needs to test product searches for multiple products.

The CSV file can contain:

product,category,expectedResult

Laptop,Electronics,Laptop

Mobile,Electronics,Mobile

Shoes,Fashion,Shoes

Book,Books,Book

Headphones,Electronics,Headphones

The automation architecture can then be:

products.csv

     |

     v

CSV Reader

     |

     v

TestNG DataProvider

     |

     v

ProductSearchTest

     |

     v

SearchPage

     |

     v

Selenium WebDriver

     |

     v

Search Results

     |

     v

Assertion

Instead of creating five separate test methods, one reusable test method can execute against all five product records.


72. Summary

CSV Data is a simple and practical way to implement data-driven testing in Selenium automation. It allows test data to be stored separately from Selenium test logic and reused across multiple test scenarios.

CSV files can contain login credentials, search keywords, registration information, product details, user roles, browser names, environment URLs, expected results, and many other types of test data.

In a TestNG framework, CSV data is commonly read using a Java utility or CSV parsing library and then supplied to test methods through a @DataProvider.

For professional automation frameworks, CSV data can be combined with Selenium WebDriver, TestNG, Page Object Model, Maven, reusable utilities, assertions, reporting, and CI/CD.

The most important practice is to keep test data, test logic, and framework infrastructure properly separated while handling CSV parsing, file paths, sensitive information, and parallel execution carefully.


73. Course Resources

Learn more about Selenium automation and professional testing concepts:

Final Takeaway: CSV-driven testing helps Selenium frameworks execute the same automation workflow against multiple external data combinations. When combined with TestNG DataProviders and Page Object Model, CSV data provides a reusable, maintainable, and scalable approach to data-driven automation testing.

whatsapp